#find_package(Protobuf 3 REQUIRED)
set(has_protoc OFF)

set(protoc_dir ${CMAKE_SOURCE_DIR}/bin/proto)
set(PROTOBUF_IMPORT_DIRS ${CMAKE_SOURCE_DIR}/bin/proto)
if(WIN32)
    if(MSVC)
        set(protoc_exe ./protoc.exe)
        set(exe_path ${CMAKE_SOURCE_DIR}/bin/proto/protoc.exe)
        set(source_path ${CMAKE_SOURCE_DIR}/Libs/bin/protobuf/Debug/protoc.exe)
    else()
        set(protoc_exe ./protoc.exe)
        set(exe_path ${CMAKE_SOURCE_DIR}/bin/proto/protoc.exe)
        set(source_path ${CMAKE_SOURCE_DIR}/Libs/bin/protobuf/protoc.exe)
    endif()
else()
    set(protoc_exe ./protoc)
    set(exe_path ${CMAKE_SOURCE_DIR}/bin/proto/protoc)
    set(source_path ${CMAKE_SOURCE_DIR}/Libs/bin/protobuf/protoc)
endif()
message(${source_path})
if(EXISTS ${exe_path})
    set(has_protoc ON)
    message("find protoc successful")
elseif(MSVC)
    if(EXISTS ${source_path})
        set(has_protoc ON)
        message("copy protoc successful")
        file(COPY ${source_path} DESTINATION ${CMAKE_SOURCE_DIR}/bin/proto)
    else()
        message(ERROR "没有找到protoc.exe")
    endif()
else()
    if(EXISTS ${source_path})
        set(has_protoc ON)
        message("copy protoc successful")
        execute_process(COMMAND cp ${source_path} ${exe_path})
    else()
        message(ERROR "没有找到protoc")
    endif()
endif()

#设置输出路径
set(MESSAGE_DIR ${CMAKE_SOURCE_DIR}/Gen/Message)
if(EXISTS "${CMAKE_SOURCE_DIR}/Gen/Message")
    SET(DST_DIR ${MESSAGE_DIR})
else()
    file(MAKE_DIRECTORY ${MESSAGE_DIR})
    SET(DST_DIR ${MESSAGE_DIR})
endif()

set(MESSAGE_SRC "")
set(MESSAGE_HDRS "")
#设置protoc的搜索路径
LIST(APPEND PROTO_FLAGS -I${CMAKE_SOURCE_DIR}/bin/proto)

#获取需要编译的proto文件
file(GLOB_RECURSE c2s_proto ${CMAKE_SOURCE_DIR}/bin/proto/c2s/*.proto)
file(GLOB_RECURSE s2s_proto ${CMAKE_SOURCE_DIR}/bin/proto/s2s/*.proto)
file(GLOB_RECURSE com_proto ${CMAKE_SOURCE_DIR}/bin/proto/com/*.proto)
file(GLOB_RECURSE com_proto ${CMAKE_SOURCE_DIR}/bin/proto/record/*.proto)
#file(GLOB_RECURSE mysql_proto ${CMAKE_SOURCE_DIR}/bin/proto/mysql/*.proto)

#execute_process(COMMAND cd ${protoc_dir})
if(has_protoc) # 生成源码
    list(APPEND proto_files ${c2s_proto} ${s2s_proto} ${com_proto} ${mysql_proto})
    foreach(protoc_file ${proto_files})
        get_filename_component(FIL_WE ${protoc_file} NAME_WE)
        list(APPEND MESSAGE_SRC "${CMAKE_SOURCE_DIR}/Gen/Message/${FIL_WE}.pb.cc")
        list(APPEND MESSAGE_HDRS "${CMAKE_SOURCE_DIR}Gen/Message/${FIL_WE}.pb.h")
        execute_process(COMMAND ${exe_path} ${PROTO_FLAGS} --cpp_out=${DST_DIR} ${protoc_file})
    endforeach()
    set_source_files_properties(${MESSAGE_SRC} ${MESSAGE_HDRS} PROPERTIES GENERATED TRUE)
else()
    message("============ please build protoc ==============")
endif()